//###############
//FILE : FileManagerInitializer.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.filemanager;


import java.util.ArrayList;

import oop.ex3.communication.SocketAddress;
import oop.ex3.protocol.sessions.FileInitSession;

/**
 * This class is in charge of initializing a file manager.
 * It's main job is to inform all of the nameservers in it's database about
 * the files and nameservers it knows about.
 * @author daniel
 */
public class FileManagerInitializer {
    private ArrayList<SocketAddress> _nameServers;
    private NameServerConnection _connection;
    
    /**
     * Create a initializer with a specific nameserver connection that will be used
     * to connect to the relevant nameservers.
     * @param connection
     */
    public FileManagerInitializer(NameServerConnection connection) {
        _nameServers = connection.getNameServerDatabase().getAddressList();
        _connection = connection;
    }

    /**
     * Initialize the file manager by updating the nameservers.
     */
    public void initFileManager() {
        for (SocketAddress nameServer : _nameServers)
            updateNameServer(nameServer);
    }

    private void updateNameServer(SocketAddress nameServer) {

        if (!_connection.initializeStreams(nameServer)) {
            return;
        }

        FileInitSession session = new FileInitSession();
        _connection.initializeSession(session);
        session.executeSession(_connection.getInputStream(),
                _connection.getOutputStream());

        _connection.closeConnection();

    }
}
